package com.it.common.utils;

import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

import java.util.HashMap;
import java.util.Locale;

public class TtsUtil {
    private static final TtsUtil INSTANCE = new TtsUtil();
    private Context mContext;
    public static final String TAG = "TtsUtil";
    TextToSpeech mTextToSpeech;

    public static TtsUtil getInstance() {
        return INSTANCE;
    }

    public void init(Context context) {
        mContext = context;
        mTextToSpeech = new TextToSpeech(context, new OnInitListener() {

            @Override
            public void onInit(int status) {
                LogUtil.d(TAG, "TtsUtil init result=" + status);
                if (status == TextToSpeech.SUCCESS) {
                    int result = mTextToSpeech.setLanguage(Locale.CHINA);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        LogUtil.d(TAG, "中文语言不支持");
                    }
                }
            }
        });
    }

    public void speak(String str) {
        LogUtil.d(TAG, "播放声音 str = " + str);
        // MediaPlayerUtils.INSTANCE.isSpeakerphoneOn( true, mContext);
        HashMap<String, String> params = new HashMap<>();
        params.put(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_ALARM + "");
        mTextToSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, params);
    }

    public void stop() {
        LogUtil.d(TAG, "停止tts");
        mTextToSpeech.stop();
    }

    public void release() {
        mTextToSpeech.stop();
        mTextToSpeech.shutdown();
    }
}
